<template>
  <div>

    <el-dialog :title="dialogTitle" :visible.sync="showDialog_" custom-class='dialog_right dialogScroll_add MkAddBanner' top="0%" @close='closeDialog("addBannerForm")' @open='openDialog'>
      <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight-200)+'px'}]">
        <el-form :model="addBannerForm.formItem" :rules="addBannerForm.rules" ref="addBannerForm" label-width="85px">
          <el-form-item label="排序" prop='sort'>
            <el-input v-model="addBannerForm.formItem.sort" placeholder='' size=""></el-input>
          </el-form-item>
          <el-form-item label="标题" prop='title'>
            <el-input v-model="addBannerForm.formItem.title" placeholder='请输入标题（必填）' size=""></el-input>
          </el-form-item>
          <el-form-item label="所属站点" prop='siteArr'>
            <el-select v-model="addBannerForm.formItem.siteArr" multiple placeholder="请选择所属站点（必选）">
              <el-option v-for="item in siteData" :label="item.name" :value="item.id" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="展示位置" prop='position'>
            <el-select v-model="addBannerForm.formItem.position" placeholder="请选择展示位置（必选）" size='' @change="changePosition">
              <el-option v-for="item in positionData" :key="item.value" :value="item.value" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传图片" prop='imageId'>
            <el-upload
              accept=".jpeg, .jpg, .png, .gif"
              class="avatar-uploader"
              :action="'/upload/image.json'"
              :show-file-list="false"
              :on-success="handleSuccess"
              :data = 'showTipObj'
              :before-upload="beforeAvatarUpload"
              name="image">
              <img v-if="dialogImageUrl" :src="dialogImageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <p v-if="showTipMsg" style="color:#83a0a5;font-size:14px;">建议上传{{showTipMsg}}规格的图片</p>
          </el-form-item>
          <el-form-item label="进入页面" prop='type' style="margin-bottom:10px;">
            <el-radio-group v-model="addBannerForm.formItem.bannerType" @change="changeBannerType">
              <el-radio label="H5">链接</el-radio>
              <el-radio label="Native">原生页面</el-radio>
            </el-radio-group>
          </el-form-item>

            <el-form-item label="" prop='linkH5'  v-show ="addBannerForm.formItem.bannerType == 'H5'" >
              <el-input v-model="addBannerForm.formItem.linkH5" placeholder='请输入链接' size=""></el-input>
            </el-form-item>
        </el-form>
        <el-form  v-if ="addBannerForm.formItem.bannerType == 'Native'" :model="addBannerForm.formItem" :rules="addBannerForm.rules" ref="otherForm" label-width="85px">
          <el-form-item label="" prop='linkNative' >
            <el-select v-model="addBannerForm.formItem.linkNative"  placeholder="请选择原生页面（必选）">
              <el-option v-for="item in nativeSelect" :label="item.name"  :value="item.value" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer footerStyle">
        <el-button type="primary" class="btn-primary" @click='submitForm("addBannerForm")' :disabled = 'isSubmitBtnDisabled' v-loading.fullscreen.lock="fullscreenLoading">保存</el-button>
        <el-button type='primary' class='btn-cancel' @click="showDialog_ = false" size=''>取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapState } from 'vuex'
import bannerService from '../../services/banner'

export default {
  name: 'MkAddBanner',
  props: ['showDialog', 'bannerInfo'],
  computed:mapState({
    bodyHeight: state => state.global.bodyHeight,
    siteData: state => {
      let children = state.site.siteTree.children;
        let arr = [];
        if(children) {
            for(let i=0;i < children.length;i++) {
                let item = children[i];
                if(item.children){
                    for(let j=0;j < item.children.length;j++) {
                        let site = item.children[j];
                        arr.push({
                          id:site.id,
                          name: site.name+'（'+item.name+'）'
                        })
                    }
                }
            }
        }
        return arr;
    },
    positionData: state => state.banner.positionSelect,
    nativeSelect: state => state.banner.nativeSelect
  }),
  methods: {
    changePosition(val) {
      if(val) {
          switch (val) {
            case 'SWSH_HOME_01':
            case 'SWSH_TOHOMESERVICES_01':
            case 'SWSH_HOUSERENTAL_01':
                this.showTipObj = {'width':900,'height':300};
                this.showTipMsg = '900*300';
                break;
            case 'SWSH_RECOMMEND_01':
            case 'SWSH_RECOMMEND_02':
            case 'SWSH_RECOMMEND_03':
            case 'SWSH_RECOMMEND_04':
              this.showTipObj = {'width':400,'height':200};
              this.showTipMsg = '400*200';
              break;
            case 'SWSH_HOME_02':
            case 'SWSH_HOUSEKEEPER_01':
              this.showTipObj = {'width':900,'height':225};
              this.showTipMsg = '900*225';
              break;
            default:
              this.showTipObj = {};
              this.showTipMsg = '';
          }
      }
    },
    loadNativeSelect() {
      bannerService.loadNativeSelectServer(data => {
          this.nativeSelect = data.data;
      })
    },
    changeBannerType() {
      this.addBannerForm.formItem.linkH5 = '';
      this.addBannerForm.formItem.linkNative = '';
    },
    handleSuccess(res, file) {
      this.dialogImageUrl = URL.createObjectURL(file.raw);
      this.addBannerForm.formItem.imageId = res.data.fileId;
      this.$refs['addBannerForm'].validateField('imageId');
//      this.changeField('addBannerForm', 'addBannerForm', 'imageId')
    },
    beforeAvatarUpload(file) {
      var fileName = file.name;
      var suffix = fileName.substr(file.name.lastIndexOf("."), fileName.length).toLowerCase();
      var support = false;
      for (var i = 0; i < this.supportFile.length; i++) {
        if (suffix == this.supportFile[i]) {
          support = true;
          break;
        }
      }
      if (!support) {
        this.$message.warning('只能上传图片格式的文件');
        return support;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!');
      }
      return isLt5M;
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields();
      var form = this.addBannerForm.formItem;
      form.id = '';
      form.sort = 1;
      form.title = '';
      form.position = '';
      form.imageId = '';
      form.link = '';
      form.linkH5 = '';
      form.linkNative = '';
      form.bannerType = 'H5';
      form.siteIds = '';
      form.siteArr = [];
      this.dialogImageUrl = '';
      this.showTipObj = {};
      this.showTipMsg = '';
      this.$emit('closeDialog', this.isRefresh);
    },
    openDialog() {
      this.isSubmitBtnDisabled = false;
      this.isRefresh = false;
      if (this.bannerInfo) {
        this.dialogTitle = '编辑banner';
        var bannerInfo = this.bannerInfo;
        var form = this.addBannerForm.formItem;
        form.id = bannerInfo.id;
        form.sort = bannerInfo.sort;
        form.title = bannerInfo.title;
        form.position = bannerInfo.position;
        form.imageId = bannerInfo.image.fileId;
        form.bannerType = bannerInfo.bannerType;
        form.siteArr = bannerInfo.siteIds;

        this.dialogImageUrl = bannerInfo.image.accessUrl;
        this.$nextTick(function(){
            if(form.bannerType == 'H5') {
              form.linkH5 = bannerInfo.linkKey;
            }else{
              form.linkNative = bannerInfo.linkKey;
            }

        })
      } else {
        this.dialogTitle = '添加banner';
      }
    },
    changeField(form, formName, field) {
      this[form].formItem[field] = (this[form].formItem[field] + '').trim();
      this.$refs[formName].validateField(field);
    },
    submitForm(formName) {
        let flag1 = false;
        let flag2 = false;
      if(this.$refs['otherForm']){
        this.$refs['otherForm'].validate((valid) => {
          if (valid) {
            flag1 = true;
          }
        })
      }else{
        flag1 = true;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          flag2 = true;
        }
      })
      if(flag1 && flag2) {
        let form = this.addBannerForm.formItem;
        form.siteIds = form.siteArr.join(',');
        if(form.bannerType == '') {
          form.link = '';
        }else if(form.bannerType == 'H5') {
          form.link = form.linkH5;
        }else if(form.bannerType == 'Native') {
          form.link = form.linkNative;
        }
        this.isSubmitBtnDisabled = true;
        this.fullscreenLoading = true;
        if (!this.bannerInfo) {
          bannerService.addBannerServer(form, (data) => {
            this.$message.success(' 添加成功');
            this.isRefresh = true;
            this.showDialog_ = false;
            this.fullscreenLoading = false;
          }, (data) => {
            this.fullscreenLoading = false;
            this.isSubmitBtnDisabled = false;
          })
        } else {
          bannerService.updateBannerServer(form, (data) => {
            this.$message.success('修改成功');
            this.isRefresh = true;
            this.showDialog_ = false;
            this.fullscreenLoading = false;
          }, (data) => {
            this.fullscreenLoading = false;
            this.isSubmitBtnDisabled = false;
          })
        }
      }
    },
  },
  mounted() {
    this.$store.dispatch('loadNativeSelect');
  },
  watch: {
    showDialog: function(value) {
      this.showDialog_ = value;
    },
  },
  data() {
    var validateSort = (rule, value, callback) => {
      let val = (value + '').trim();
      if (val === '') {
        callback(new Error('请输入排序'));
      } else {
        let reg = /^[1-9]\d{0,3}$/;
        if (!reg.test(val)) {
          callback(new Error('只能输入整数，最多4位'));
        }
        callback();
      }
    };
    var validateLink = (rule, val, callback) => {
      if (val === '') {
          callback(new Error('请选择原生页面'));
      } else {
        callback();
      }
    }
    return {
      showTipObj: {},
      showTipMsg: '',
      dialogTitle: '',
      isSubmitBtnDisabled: false,
      clickSubmitBtn: false,
      fullscreenLoading: false,
      supportFile: ['.jpeg', '.jpg', '.png', '.gif'],
      isRefresh: false,
      dialogImageUrl: '',
      showDialog_: this.showDialog,
      addBannerForm: {
        formItem: {
          id: '',
          sort: '1',
          title: '',
          position: '',
          imageId: '',
          link: '',
          siteIds: '',
          bannerType: 'H5',

          linkH5: '',
          linkNative: '',

          siteArr: [],
        },
        rules: {
          siteArr: { required: true, type: 'array', message: '请选择所属站点', trigger:'change,blur'  },
          sort: [
            { validator: validateSort,trigger:'change,blur'  },
          ],
          title: [
            { required: true, message: '请输入标题' ,trigger:'change,blur' }
          ],
          position: [
            { required: true, message: '请选择展示位置' ,trigger:'change,blur'}
          ],
          imageId: [
            { required: true, type:'number', message: '请上传图片',trigger:'change,blur'  }
          ],
          linkNative:  { validator: validateLink, trigger:'change,blur'  },
        }
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #3bc0c3;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
